package com.htgd.gardenexpo.controller;

import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.page.ComplaintQuery;
import com.htgd.gardenexpo.service.GeBaseUserService;
import com.htgd.gardenexpo.service.GeConComplaintService;
import com.htgd.gardenexpo.service.GeConComplaintUploadService;
import com.htgd.gardenexpo.service.GePhoneComplaintsService;
import com.htgd.gardenexpo.utils.GetAmazonS3Client;
import com.htgd.gardenexpo.utils.SecurityParameter;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：hejing
 * @date ：Created in 2021/5/25 9:39
 * @description：投诉举报管理
 * @menu: 投诉举报管理
 * @modified By：`
 * @version: 1.0
 */
@Api(tags = "投诉举报管理")
@RestController
@RequestMapping("/api/complaints")
public class ComplaintsController {

    @Value("${upload.url}")
    public String upload_url;
    @Value("${spring.file-storage.aws-s3[0].bucket-name}")
    public String bucket_name;

    @Autowired
    private FileStorageService fileStorageService;

    @Resource
    private GetAmazonS3Client getAmazonS3Client;

    @Resource
    private GeConComplaintService geConComplaintService;

    @Resource
    private GeConComplaintUploadService geConComplaintUploadService;

    @Resource
    private GeBaseUserService geBaseUserService;

    @Autowired
    private GePhoneComplaintsService gePhoneComplaintsService;

    /**
     * 游客投诉信息列表查询（支持翻页）
     */
    @GetMapping(value = "/list")
    public CommonResult<List<Map<String,Object>>> list(){
        CommonResult<List<Map<String, Object>>> result = new CommonResult<>();

        return result;
    }

    /**
     * 游客投诉信息详情
     */
    @GetMapping(value = "/details")
    public CommonResult<Map<String,Object>> details(int complaintId){
        CommonResult<Map<String,Object>> result = new CommonResult<>();
        try{
//            Integer complaintId=JSON.parseObject(s).getInteger("complaintId");
            Map<String, Object> map = new HashMap<>();
            GeConComplaint geConComplaint=geConComplaintService.queryById(complaintId);
            map.put("complaint",geConComplaint);
            List<GeConComplaintUpload> geConComplaintUploads=geConComplaintUploadService.queryByComplaintId(complaintId);
            map.put("upload",geConComplaintUploads);
            GeBaseUser geBaseUser=geBaseUserService.queryById(geConComplaint.getUserId());
            map.put("user",geBaseUser);
            //手机号
            GePhoneComplaints gePhoneComplaints = gePhoneComplaintsService.queryById(1);
            map.put("phone",gePhoneComplaints.getComplaintPhone());
            result.setCode(200);
            result.setData(map);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 游客投诉信息回复反馈
     */
    @GetMapping(value = "/reply")
    public CommonResult<JSONObject> reply(@RequestBody GeConComplaint geConComplaint){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            geConComplaint.setReplyTime(new Date());
            geConComplaintService.update(geConComplaint);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }


    /**
     * 游客投诉信息重点标记
     */
    @GetMapping(value = "/mark")
    public CommonResult<JSONObject> mark(@RequestBody GeConComplaint geConComplaint){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            geConComplaintService.update(geConComplaint);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 游客投诉信息下载
     */
    @GetMapping(value = "/download")
    public CommonResult<JSONObject> dowmload(){
        CommonResult<JSONObject> result = new CommonResult<>();
        return result;
    }




    /**
     * 新增投诉信息
     */
    @PostMapping(value = "/add")
    @SecurityParameter
    public CommonResult<JSONObject> add(@RequestBody GeConComplaint geConComplaint){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            geConComplaintService.insert(geConComplaint);
            String uploadIds=geConComplaint.getUploadIds();
            if (!uploadIds.equals("")&&uploadIds.contains(",")){
                for (String uploadId:uploadIds.split(",")){
                    GeConComplaintUpload geConComplaintUpload =geConComplaintUploadService.queryById(Integer.parseInt(uploadId));
                    geConComplaintUpload.setComplaintId(geConComplaint.getComplaintId());
                    geConComplaintUploadService.update(geConComplaintUpload);
                }
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 上传文件
     */
    @PostMapping(value = "/uploadFile")
    public GeConComplaintUpload uploadFile(@RequestParam(value = "file") MultipartFile file){

        GeConComplaintUpload geConComplaintUpload = new GeConComplaintUpload();
        String fileName = file.getOriginalFilename();  // 文件名
        geConComplaintUpload.setFilename(fileName);
        FileInfo fileInfo=fileStorageService.of(file)
                .setPlatform("aws-s3-1")
                .setSaveFilename(System.currentTimeMillis()+"/"+file.getOriginalFilename())
                .upload();
        geConComplaintUpload.setFilePath(upload_url+fileInfo.getFilename());
        geConComplaintUploadService.insert(geConComplaintUpload);
        return geConComplaintUpload;
    }

    /**
     * 编辑投诉信息
     */
    @PostMapping(value = "/edit")
    public CommonResult<JSONObject> edit(@RequestBody GeConComplaint geConComplaint){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            if (geConComplaint.getStatus()==1){
                geConComplaint.setReplyTime(new Date());
            }
            geConComplaintService.update(geConComplaint);
            String uploadIds=geConComplaint.getUploadIds();
            if (!uploadIds.equals("")&&uploadIds.contains(",")){
                geConComplaintUploadService.deleteByIds(uploadIds.split(","),geConComplaint.getComplaintId());
                for (String uploadId:uploadIds.split(",")){
                    GeConComplaintUpload geConComplaintUpload =geConComplaintUploadService.queryById(Integer.parseInt(uploadId));
                    geConComplaintUpload.setComplaintId(geConComplaint.getComplaintId());
                    geConComplaintUploadService.update(geConComplaintUpload);
                }
            }else {
                geConComplaintUploadService.deleteByComplaintId(geConComplaint.getComplaintId());
            }
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 删除投诉信息
     */
    @PostMapping(value = "/delete")
    @SecurityParameter
    public CommonResult<JSONObject> delete(@RequestBody String s){
        CommonResult<JSONObject> result = new CommonResult<>();
        try{
            Integer complaintId= JSON.parseObject(s).getInteger("complaintId");
            geConComplaintService.deleteById(complaintId);
            List<GeConComplaintUpload> list=geConComplaintUploadService.queryByComplaintId(complaintId);
            for (GeConComplaintUpload geConComplaintUpload:list){
                String filepath=geConComplaintUpload.getFilePath();
                String path=filepath.substring(filepath.indexOf(bucket_name+"/"),filepath.length()-1);
                getAmazonS3Client.delete(path);
            }
            geConComplaintUploadService.deleteByComplaintId(complaintId);
            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 批量删除投诉信息
     */
//    @PostMapping(value = "/deleteAll")
    public CommonResult<JSONObject> deleteAll(String complaintIds){
        CommonResult<JSONObject> result = new CommonResult<>();
        try {
            if (complaintIds!=null&&!complaintIds.equals("")){
                for (String promo:complaintIds.split(",")){
                    int promoId= Integer.parseInt(promo);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("complaintId",promoId);
                    delete(jsonObject.toJSONString());
                }
            }

            result.setCode(200);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }

    /**
     * 检索投诉举报历史（支持翻页）
     */
    @PostMapping(value = "/historylist")
    @SecurityParameter
    public CommonResult<List<GeConComplaint>> historylist(@RequestBody ComplaintQuery complaintQuery){
        CommonResult<List<GeConComplaint>> result = new CommonResult<>();
        try{
            PageHelper.startPage(complaintQuery.getPageNum(),complaintQuery.getPageSize());
            List<GeConComplaint> list = geConComplaintService.list(complaintQuery);
            //Long count = geConComplaintService.count(complaintQuery);
            //List<GeConComplaint> list=geConComplaintService.getAllComplaintByValue(pageQuery);
            //pageQuery.setPageSize(0);
            //List<GeConComplaint> list1=geConComplaintService.getAllComplaintByValue(pageQuery);
            //List<GePhoneComplaints> list2=gePhoneComplaintsService.queryAllByLimit(0,0);
            //String searchPhone = list2.get(0).getSearchPhone();
            //for (GeConComplaint geConComplaint : list) {
                //geConComplaint.setSearchPhone(searchPhone);
            //}
            result.setCode(200);
            result.setData(new PageInfo<>(list).getList());
            result.setMessage(String.valueOf(new PageInfo<>(list).getTotal()));
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(500);
        }
        return result;
    }





}
